package com.gin.kotlin.no_gay_alliance.adapter

import android.content.Context
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Typeface
import android.view.View
import com.gin.kotlin.no_gay_alliance.R
import com.gin.kotlin.no_gay_alliance.activity.ReplyListActivity
import com.gin.kotlin.no_gay_alliance.argument.ReplyListArgument
import com.gin.kotlin.no_gay_alliance.base.AbstractBindingRecyclerViewAdapter
import com.gin.kotlin.no_gay_alliance.base.MyHandler
import com.gin.kotlin.no_gay_alliance.database.entity.TopicHistory
import com.gin.kotlin.no_gay_alliance.databinding.ItemTopicBinding
import com.gin.kotlin.no_gay_alliance.utils.TimeUtils.Companion.zdtIntoTextView

class TopicHistoryAdapter(context: Context, handler: MyHandler) : AbstractBindingRecyclerViewAdapter<ItemTopicBinding, TopicHistory>(context, handler), View.OnClickListener {
    override fun onBindViewHolder(holder: ViewHolder<ItemTopicBinding>, position: Int, b: ItemTopicBinding, dataModel: TopicHistory) {
        b.checkBox.visibility = View.GONE

        // 主题标题
        val attrColor = getAttrColor(R.attr.textColor)
        b.tvTopicTitle.also { tv ->
            tv.text = dataModel.title
            // 默认颜色
            tv.setTextColor(attrColor)

            tv.setTypeface(null)
            // 颜色
            tv.setTextColor(
                if (dataModel.titleColor == null ) attrColor
                else Color.parseColor( dataModel.titleColor.rgb)
            )
            // 标题字体：加粗、删除、斜体
            tv.paintFlags = tv.paintFlags and (Paint.STRIKE_THRU_TEXT_FLAG.inv())
            // 加粗
            if (dataModel.bold) tv.setTypeface(tv.typeface, Typeface.BOLD)
            // 斜体
            if (dataModel.italic) tv.setTypeface(tv.typeface, Typeface.ITALIC)
            // 删除线
            if (dataModel.lineThrough) tv.paintFlags = tv.paintFlags or Paint.STRIKE_THRU_TEXT_FLAG

        }

        b.tvForumName.text = dataModel.topicParent?.let { "[$it]" }
        b.tvAuthorName.text = dataModel.authorName
        b.tvLastPosterName.text = "${dataModel.lastPosterName}(${dataModel.replies})"

        dataModel.postDatetime?.also { zdtIntoTextView(context, it, b.tvPostTime, attrColor) }

        dataModel.timestamp.also { zdtIntoTextView(context, it, b.tvUserReply, attrColor) }
        b.tvUserReplyTime.text = "看到第 ${dataModel.page} 页"

        b.root.tag = dataModel
        b.root.setOnClickListener(this)
    }

    override fun onClick(v: View?) {
        val topicHistory = v?.tag as? TopicHistory ?: return
        ReplyListActivity.startActivity(context, ReplyListArgument(ReplyListArgument.Type.LIST, topicId = topicHistory.topicId, targetPage = topicHistory.page, totalPage = topicHistory.page))
    }
}